package com.example.coroutinelearn.down_load_demo

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.ResponseBody
import okio.IOException
import java.io.File

/**
 * @author huangzehui
 * @date 7/6/2024 下午11:17 周五
 * @description
 */
object DownloadManager {


    fun download(url: String, file: File): Flow<DownloadState> {

        return flow {
            val request = Request.Builder()
                .url(url)
                .get()
                .build()
            val result = OkHttpClient.Builder()
                .build()
                .newCall(request).execute()
            if (result.isSuccessful) {

                result.body!!.let { body: ResponseBody ->
                    val contentLength = body.contentLength()

                    file.outputStream().use { output ->

                        val byteStream = body.byteStream()
                        byteStream.copyTo(output) { byteCopied ->
                            val progress = byteCopied * 100 / contentLength

                            emit(DownloadState.Progress(progress.toInt(), 100))
                        }
                    }
                }
                emit(DownloadState.Done(file))
            } else {
                throw IOException(result.toString())
            }
        }.catch {
            file.delete()
            emit(DownloadState.Error(it))
        }.flowOn(Dispatchers.IO)
    }

}